package com.linjacy.httpproject.util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @Auther: jc
 * @Date: 2021/3/31 10:19
 * @Description:RSA工具类
 */
public class RSAUtil {

    public static PublicKey publicKey;

    public static PrivateKey privateKey;

    public static String rsaEncryptOAEP(String message, PublicKey publicKey)
            throws IllegalBlockSizeException, IOException {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            byte[] data = message.getBytes("utf-8");
            byte[] cipherdata = cipher.doFinal(data);
            return Base64.getEncoder().encodeToString(cipherdata);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException("当前Java环境不支持RSA v1.5/OAEP", e);
        } catch (InvalidKeyException e) {
            throw new IllegalArgumentException("无效的公钥", e);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new IllegalBlockSizeException("加密原串的长度不能超过214字节");
        }
    }

    public static String rsaDecryptOAEP(String ciphertext, PrivateKey privateKey)
            throws BadPaddingException, IOException {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            byte[] data = Base64.getDecoder().decode(ciphertext);
            return new String(cipher.doFinal(data), "utf-8");
        } catch (NoSuchPaddingException | NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA v1.5/OAEP", e);
        } catch (InvalidKeyException e) {
            throw new IllegalArgumentException("无效的私钥", e);
        } catch (BadPaddingException | IllegalBlockSizeException e) {
            throw new BadPaddingException("解密失败");
        }
    }

    static {

        try {

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] publicKeybyte = Base64.getDecoder().decode("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo8P6NVzlFlI4+SNb8/F+8T5x+a0TcsaqRN2dTAZUf1/x4wDXlwpExKfYhhylVGR56QpfQOpF7op/lcfv2ZtInckyE4iVkqqDFAedA2G+3Ov2AQhs1RCO9GVGzOoqOZ2olF0m6SyHQIC3gfmUIoZqU35CaTLT66Nk8xz0E2Nas3cjabjf0SmD8h2pZxQr8b6bG0fueN99OnJQXjQ7CcAY6bSD3mWknndHi8rd1SygUXRMsXsetleJMi+p3qGO0GHDDOn8G9pd9zZJvkf2FyGAnD2vMz+xyrwsWFP3d7tbjsT1IS0jCSOhzG8hiowIIY2mcNY+CijvX+JXs6kl+MrrmwIDAQAB");
            byte[] privateKeybyte = Base64.getDecoder().decode("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCjw/o1XOUWUjj5I1vz8X7xPnH5rRNyxqpE3Z1MBlR/X/HjANeXCkTEp9iGHKVUZHnpCl9A6kXuin+Vx+/Zm0idyTITiJWSqoMUB50DYb7c6/YBCGzVEI70ZUbM6io5naiUXSbpLIdAgLeB+ZQihmpTfkJpMtPro2TzHPQTY1qzdyNpuN/RKYPyHalnFCvxvpsbR+543306clBeNDsJwBjptIPeZaSed0eLyt3VLKBRdEyxex62V4kyL6neoY7QYcMM6fwb2l33Nkm+R/YXIYCcPa8zP7HKvCxYU/d3u1uOxPUhLSMJI6HMbyGKjAghjaZw1j4KKO9f4lezqSX4yuubAgMBAAECggEAYR6OOitXKL+mTgnsNGVZlRQlX56G1CCBRcnvyPBQGCH8P1V2hXpvgfjQbeh7G+tiaRPfnY3R3z9/noIt+e0fSYPSEMeFfK9mgPBq62CCYl4FTGOEt27UeJe/PzL3y6d2HFaKBuqDY3tyWMB8W2U/lThhhiXAjBQggBUBoqXfWmIvKfL0egO6TOA3cUOIlLbiH0HFkLMDFcp4xL/ef/UgcE9qTXl+13uPG03MswA6JUpSW6QwyB+f/owYsSSaA8+XYAmdapAjsx1j6UcQ7Hc24lHE/VwwOLfmJyvARjyCmAwq+2BOShyBkka6OILRh+K+VUyWLuBLVb4HqBc1rYyJAQKBgQDiRsE4B01/dvhfzL+YAUGnyvhEXY47cU+EabQmkhbru7dYZsEypVZ9MU4/pqNbLROrGQ4ojmemDAl8f6qHgkDR1UCjd8f84/mZlQsTo25OnHQdv8cWegslnAjh5fxDyALPQAJNRSwHwO6/Go+LneF9nchdAbnmALTZ+6fhs8QBQQKBgQC5Rxn4MWbMRBBhDhem0Lr6kkV9OLrevgU7VCYOstapb30HBg/izCa28Xmgo9Ogc1ltez4nRx2wz+N/hpUMwZwh+ZGE4FEmJ7bxv1RzWZo5ArHErNwzbFrhF4Urc1ZAwWDrxj7VpOl+uy5Pf7+BkX1aSl+Y84Y4dBnyFEeFtd6Z2wKBgQC1V/VEXP3sGMHHrUUjomYm/pDn4X66/v22Ziyd+Njrxf6Tl45gc4eUP+6xLnCfAspPhn4FXNOOjPkRUROvFGG0iU8Lc1TQxThlsMA21fTyhYq9yNPanKbQVnP77yC0hdhSlr8BhF1cPXBZsgS25SoxTUGl4FtHDOvkAz6xsSt1wQKBgGy4fVO34YOx2Q6qz1QzHdVVqfMuK/Hy/WzwFxj+9poccviBJSdH9tvZXS7Xk6KOrYZiEHnJ8HFFvFCj76i5n94L7clUPCowmdjIFk1N4gLcQuaPLPP7/GQjgiCaIJ4FG9Oe1FZX3DBitG0wIHduoWkvRWOiWzubXXJBVirvKv2LAoGBAN4tn9ClErUItJN8Er2Tv0JRvRx9RwlT/VswJXiKbGIIA1/r2Jb9O/REEbJYIlX7K7DiiMO2LLjNZTFYlH7WaHP3i9E0A+sRJ2WreoK/feprdUB/r+pZM2xncKs+e7vTB2CC0mPCNjUqq2MZSrg5I0OznrEn5C/bRj2jjebkwwKO");
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeybyte);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeybyte);
            publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        try {
            System.out.println(RSAUtil.rsaEncryptOAEP("{\"userName\":\"testDecrypt\",\n" +
                    "    \"password\":\"root\"}", publicKey));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
    }

}
